package com.example.pixelyear.ui.act

import android.os.Bundle
import androidx.fragment.app.Fragment
import androidx.viewpager.widget.ViewPager
import com.example.pixelyear.R
import com.example.pixelyear.adapter.BaseAdapter
import com.example.pixelyear.adapter.IndicatorAdapter
import com.example.pixelyear.adapter.SimplePagerTKAdapter
import com.example.pixelyear.ui.base.BaseActivity
import com.example.pixelyear.ui.base.BaseFragment
import com.example.pixelyear.ui.frag.YearViewFragment
import com.example.pixelyear.utils.Constant
import com.example.pixelyear.utils.DefaultHandler
import com.example.pixelyear.utils.Utils
import com.example.pixelyear.utils.YxsSpUtils
import com.example.pixelyear.utils.extension.horizontalManager
import com.socks.library.KLog
import kotlinx.android.synthetic.main.activity_year_view.*

/**
 * 年历视图
 *
 * @author 坐怀灬不乱
 * Date 2020/10/10
 */
class YearViewActivity : BaseActivity() {
    private val mFragment = mutableListOf<BaseFragment>()
    private val mAdapter by lazy {
        IndicatorAdapter(mActivity)
    }

    override fun getLayoutResID(): Int {
        return R.layout.activity_year_view
    }

    override fun initView(bundle: Bundle?) {
        YearView_Indicator.horizontalManager()
        YearView_Indicator.adapter = mAdapter
    }

    override fun initData() {
        val year = Utils.getYear()

        val firstYear = YxsSpUtils.getInt(Constant.FIRST_ENTER_APP_YEAR, year)

        val indicator = mutableListOf<Int>()
        val nowYearIndex = (firstYear..year).indexOf(year)

        mFragment.add(YearViewFragment.getInstance(year))
        val simplePagerTKAdapter = SimplePagerTKAdapter(supportFragmentManager, mFragment)
        YearView_Page.adapter = simplePagerTKAdapter

        var thisYear: Int
        //倒叙插入
        for (i in 0..nowYearIndex) {
            thisYear = firstYear + nowYearIndex - i
            if (thisYear != year)
                mFragment.add(0, YearViewFragment.getInstance(thisYear))
            indicator.add(i)
        }
        simplePagerTKAdapter.notifyDataSetChanged()
        YearView_Page.currentItem = nowYearIndex

        mAdapter.updateList(indicator)
        mAdapter.updatePosition(mFragment.size - 1)

    }

    override fun initListener() {
        YearView_Page.addOnPageChangeListener(object : ViewPager.OnPageChangeListener {
            override fun onPageScrollStateChanged(state: Int) {

            }

            override fun onPageScrolled(
                position: Int,
                positionOffset: Float,
                positionOffsetPixels: Int
            ) {
            }

            override fun onPageSelected(position: Int) {
                mAdapter.updatePosition(position)
            }
        })

        mAdapter.setOnItemClickListener(object : BaseAdapter.OnItemClick<Int> {
            override fun click(bean: Int, position: Int) {
                YearView_Page.currentItem = position
            }
        })
    }

}
